package io.wongxd.solution.compose.helper

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.core.content.FileProvider
import io.wongxd.solution.permission.core.rememberMultiplePermissionsState
import io.wongxd.solution.permission.core.rememberPermissionState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.io.File
import java.util.UUID

// AndroidManifest.xml

// <uses-permission android:name="android.permission.CAMERA" />
//
//    <uses-permission
//        android:name="android.permission.READ_EXTERNAL_STORAGE"
//        android:maxSdkVersion="31" />
//
//    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
//
//    <uses-feature
//        android:name="android.hardware.camera"
//        android:required="false" />
//
//    <provider
//            android:name="androidx.core.content.FileProvider"
//            android:authorities="${applicationId}.image.provider"
//            android:exported="false"
//            android:grantUriPermissions="true">
//            <meta-data
//                android:name="android.support.FILE_PROVIDER_PATHS"
//                android:resource="@xml/file_provider_paths" />
//        </provider>


// file_provider_paths.xml

//<?xml version="1.0" encoding="utf-8"?>
//<paths>
//    <external-path
//        name="img_files"
//        path="." />
//    <cache-path
//        name="cache"
//        path="." />
//
//</paths>


//     val mediaAction by lazy { PhotoHelper.instance }
//
//    mediaAction.Register(galleryCallback = {
//        it.uri?.let { uri ->
//            images.add(uri)
//        }
//    }, graphCallback = {
//        it.uri?.let { uri ->
//            images.add(uri)
//        }
//    })
//
//     mediaAction.takePhoto()

class SelectPicture : ActivityResultContract<Unit?, PictureResult>() {

    private var context: Context? = null

    override fun createIntent(context: Context, input: Unit?): Intent {
        this.context = context
        return Intent(Intent.ACTION_PICK).setType("image/*")
    }

    override fun parseResult(resultCode: Int, intent: Intent?): PictureResult {
        return PictureResult(intent?.data, resultCode == Activity.RESULT_OK)
    }
}

/** 图片结果 **/
class PictureResult(val uri: Uri?, val isSuccess: Boolean)

class TakePhoto : ActivityResultContract<Unit?, PictureResult>() {

    var outUri: Uri? = null
    private var imageName: String? = null

    companion object {
        //定义单例的原因是因为拍照返回的时候页面会重新实例takePhoto，导致拍照的uri始终为空
        val instance get() = Helper.obj
    }

    private object Helper {
        val obj = TakePhoto()
    }

    override fun createIntent(context: Context, input: Unit?): Intent =
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { intent ->
            getFileDirectory(context)?.let {
                outUri = it
                intent.putExtra(MediaStore.EXTRA_OUTPUT, it).apply {
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
            }
        }

    override fun parseResult(resultCode: Int, intent: Intent?): PictureResult {
        return PictureResult(outUri, resultCode == Activity.RESULT_OK)
    }

    private fun getFileDirectory(context: Context): Uri? {//获取app内部文件夹
        imageName = "img_${UUID.randomUUID().toString().substring(0, 7)}"
        val fileFolder = File(context.cacheDir, "test_imgs")
        if (!fileFolder.exists()) {
            fileFolder.mkdirs()
        }
        val file = File(fileFolder, "${imageName}.jpeg")
        if (!file.exists()) {
            file.createNewFile()
        }
        return FileProvider.getUriForFile(context, "${context.packageName}.image.provider", file)
    }
}

class PhotoHelper {

    private var openGalleryLauncher: ManagedActivityResultLauncher<Unit?, PictureResult>? = null
    private var takePhotoLauncher: ManagedActivityResultLauncher<Unit?, PictureResult>? = null

    private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    companion object {
        val instance get() = Helper.obj
    }

    private object Helper {
        val obj = PhotoHelper()
    }

    //监听拍照权限flow
    private val checkCameraPermission =
        MutableSharedFlow<Boolean?>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

    private fun setCheckCameraPermissionState(value: Boolean?) {
        scope.launch {
            checkCameraPermission.emit(value)
        }
    }

    //相册权限flow
    private val checkGalleryImagePermission =
        MutableSharedFlow<Boolean?>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

    private fun setCheckGalleryPermissionState(value: Boolean?) {
        scope.launch {
            checkGalleryImagePermission.emit(value)
        }
    }

    /**
     * @param galleryCallback 相册结果回调
     * @param graphCallback 拍照结果回调
     * @param permissionRationale 权限拒绝状态回调
     **/
    @Composable
    fun Register(
        galleryCallback: (selectResult: PictureResult) -> Unit,
        graphCallback: (graphResult: PictureResult) -> Unit,
        permissionRationale: ((gallery: Boolean) -> Unit)? = null,
    ) {
        val rememberGraphCallback = rememberUpdatedState(newValue = graphCallback)
        val rememberGalleryCallback = rememberUpdatedState(newValue = galleryCallback)
        openGalleryLauncher = rememberLauncherForActivityResult(contract = SelectPicture()) {
            rememberGalleryCallback.value.invoke(it)
        }
        takePhotoLauncher = rememberLauncherForActivityResult(contract = TakePhoto.instance) {
            rememberGraphCallback.value.invoke(it)
        }

        // todo android 13 兼容
//        val readGalleryPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//            // 13 以上的权限申请
//            Manifest.permission.READ_MEDIA_IMAGES
//        } else {
//            Manifest.permission.READ_EXTERNAL_STORAGE
//        }

        val readGalleryPermission = Manifest.permission.READ_EXTERNAL_STORAGE

        val permissionCameraState = rememberSaveable { mutableStateOf(false) }
        val permissionGalleryState = rememberSaveable { mutableStateOf(false) }
        val permissionList = arrayListOf(
            Manifest.permission.CAMERA,
            readGalleryPermission,
        )
        val galleryPermissionState = rememberPermissionState(readGalleryPermission)
        val cameraPermissionState = rememberMultiplePermissionsState(permissionList)
        LaunchedEffect(Unit) {
            checkCameraPermission.collectLatest {
                permissionCameraState.value = it == true
                if (it == true) {
                    if (cameraPermissionState.allPermissionsGranted) {
                        setCheckCameraPermissionState(null)
                        takePhotoLauncher?.launch(null)
                    } else if (cameraPermissionState.shouldShowRationale) {
                        setCheckCameraPermissionState(null)
                        permissionRationale?.invoke(false)
                    } else {
                        cameraPermissionState.launchMultiplePermissionRequest()
                    }
                }
            }
        }
        LaunchedEffect(Unit) {
            checkGalleryImagePermission.collectLatest {
                permissionGalleryState.value = it == true
                if (it == true) {
                    if (galleryPermissionState.hasPermission) {
                        setCheckGalleryPermissionState(null)
                        openGalleryLauncher?.launch(null)
                    } else if (galleryPermissionState.shouldShowRationale) {
                        setCheckGalleryPermissionState(null)
                        permissionRationale?.invoke(true)
                    } else {
                        galleryPermissionState.launchPermissionRequest()
                    }
                }
            }
        }
        LaunchedEffect(cameraPermissionState.allPermissionsGranted) {
            if (cameraPermissionState.allPermissionsGranted && permissionCameraState.value) {
                setCheckCameraPermissionState(null)
                takePhotoLauncher?.launch(null)
            }
        }
        LaunchedEffect(galleryPermissionState.hasPermission) {
            if (galleryPermissionState.hasPermission && permissionGalleryState.value) {
                setCheckGalleryPermissionState(null)
                openGalleryLauncher?.launch(null)
            }
        }
    }

    //调用选择图片功能
    fun selectImage() {
        setCheckGalleryPermissionState(true)
    }

    //调用拍照
    fun takePhoto() {
        setCheckCameraPermissionState(true)
    }

}